package com.abyss.batch;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author Abyss
 * @date 2020/10/4
 * @description
 */
public class BatchWordCountDemo {

    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        // 2. 获取数据（数据输入)
        DataSource<String> source = env.fromElements(
                "hadoop spark hadoop",
                "spark hadoop spark",
                "hadoop flink spark"
        );


        // 3. 数据处理
        FlatMapOperator<String, String> flatMap = source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        MapOperator<String, Tuple2<String, Integer>> wordWithOne = flatMap.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });

        // 按照单词进行分组
        UnsortedGrouping<Tuple2<String, Integer>> grouped = wordWithOne.groupBy(0);

        AggregateOperator<Tuple2<String, Integer>> result = grouped.sum(1);


        // 4. 输出
        result.print();
    }
}
